﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DevExpress.Web;
using TheHeGeo.Util;
using TheHeGeoDao;

namespace TheHeGeo.UserControl
{
    public partial class UcUserWarningManager : System.Web.UI.UserControl
    {
        private static List<Int32> lDuAn = new List<int>(); 
        private static List<string> lThietBi = new List<string>();
        private static int maDuan = -99999;
        private static string maThietBi ="";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                lDuAn.Clear();
                lThietBi.Clear();
                LoadDuAnCbb();
                LoadThietBiCbb();
                LoadSensorCbb();
                LoadUserCbb();
                LoadGrv();
            }
            else
            {
                //if(!string.IsNullOrEmpty(maThietBi))
                //    LoadSensorCbbByThietBi();
                //if(maDuan!=-99999)
                //    LoadThietBiCbbByDuAn();
                grvData.DataSource = Session["USER_WARNING"];
            }
        }
        protected void LoadUserCbb()
        {
            var us = ((SessionUser)Session[SessionConst.SES_USER]).NguoiSuDung.UserName;
            var user = (
                        from d in DaoHelper.Entities.PhanQuyenDuAns
                        join p in DaoHelper.Entities.DuAns on d.MaDuAn equals p.MaDuAn
                        where(p.UserName == us)
                        select new
                        {
                            d.UserName
                        }
                ).Distinct().ToList();
            var cbb = grvData.Columns["UserName"] as GridViewDataComboBoxColumn;
            cbb.PropertiesComboBox.Items.Clear();
            cbb.PropertiesComboBox.ValueType = typeof(string);
            cbb.PropertiesComboBox.ValueField = "UserName";
            cbb.PropertiesComboBox.TextField = "UserName";
            cbb.PropertiesComboBox.DataSource = user;
            
        }
        protected void LoadSensorCbb()
        {
            var us = ((SessionUser)Session[SessionConst.SES_USER]).NguoiSuDung.UserName;
            var project = (from s in DaoHelper.Entities.Sensors
                           where (lThietBi.Contains(s.MaThietBi))
                           select new
                           {
                               s.MaSensor,
                               s.TenSensor
                           }
                ).ToList();
            var cbb = grvData.Columns["MaSensor"] as GridViewDataComboBoxColumn;
            cbb.PropertiesComboBox.Items.Clear();
            cbb.PropertiesComboBox.ValueType = typeof(string);

            foreach (var s in project)
            {
                cbb.PropertiesComboBox.Items.Add(s.TenSensor, s.MaSensor);
            }
        }
        protected void LoadSensorCbbByThietBi()
        {
            var us = ((SessionUser)Session[SessionConst.SES_USER]).NguoiSuDung.UserName;
            var project = (from s in DaoHelper.Entities.Sensors
                           where (s.MaThietBi==maThietBi)
                           select new
                           {
                               s.MaSensor,
                               s.TenSensor
                           }
                ).ToList();
            var cbb = grvData.Columns["MaSensor"] as GridViewDataComboBoxColumn;
            cbb.PropertiesComboBox.Items.Clear();
            cbb.PropertiesComboBox.ValueType = typeof(string);

            foreach (var s in project)
            {
                cbb.PropertiesComboBox.Items.Add(s.TenSensor, s.MaSensor);
            }
        }
        protected void LoadThietBiCbb()
        {
            var project = (from d in DaoHelper.Entities.ThietBis
                           where (lDuAn.Contains(d.MaDuAn)&& d.Status==0)
                           select new
                           {
                               d.MaThietBi,
                               d.TenThietBi
                           }
                ).ToList();
            lThietBi.Clear();
            var cbb = grvData.Columns["MaThietBi"] as GridViewDataComboBoxColumn;
            cbb.PropertiesComboBox.Items.Clear();
            cbb.PropertiesComboBox.ValueType = typeof(string);
            if (project.Count > 0)
            {
                foreach (var s in project)
                {
                    cbb.PropertiesComboBox.Items.Add(s.TenThietBi, s.MaThietBi);
                    lThietBi.Add(s.MaThietBi);
                }
            }
            else
            {
                cbb.PropertiesComboBox.Items.Clear();
                var cbSensor = grvData.Columns["MaSensor"] as GridViewDataComboBoxColumn;
                cbSensor.PropertiesComboBox.Items.Clear();
                lThietBi.Clear();
            }
        }
        protected void LoadThietBiCbbByDuAn()
        {
            var eq = (from d in DaoHelper.Entities.ThietBis
                           where (d.MaDuAn == maDuan && d.Status == 0)
                           select new
                           {
                               d.MaThietBi,
                               d.TenThietBi
                           }
                ).ToList();
            lThietBi.Clear();
            var cbb = grvData.Columns["MaThietBi"] as GridViewDataComboBoxColumn;
            cbb.PropertiesComboBox.Items.Clear();
            cbb.PropertiesComboBox.ValueType = typeof(string);
            cbb.PropertiesComboBox.ValueField = "MaThietBi";
            if (eq.Count > 0)
            {
                maThietBi = eq[0].MaThietBi;
                foreach (var s in eq)
            {
                cbb.PropertiesComboBox.Items.Add(s.TenThietBi, s.MaThietBi);
                lThietBi.Add(s.MaThietBi);
            }
            }
            else
            {
                cbb.PropertiesComboBox.Items.Clear();
                var cbSensor = grvData.Columns["MaSensor"] as GridViewDataComboBoxColumn;
                cbSensor.PropertiesComboBox.Items.Clear();
                lThietBi.Clear();
            }   
        }
        protected void LoadDuAnCbb()
        {
            var us = ((SessionUser)Session[SessionConst.SES_USER]).NguoiSuDung.UserName;
            var project = (from p in DaoHelper.Entities.DuAns
                join u in DaoHelper.Entities.PhanQuyenDuAns on p.MaDuAn equals u.MaDuAn
                where (u.UserName == us)
                select new
                       {
                           p.MaDuAn,
                           p.TenDuAn
                       }
                ).ToList();
            lDuAn.Clear();
            var cbb = grvData.Columns["MaDuAn"] as GridViewDataComboBoxColumn;
            cbb.PropertiesComboBox.Items.Clear();
            cbb.PropertiesComboBox.ValueType = typeof(int);
            //cbb.PropertiesComboBox.ValueField = "MaDuAn";
            //cbb.PropertiesComboBox.TextField = "TenDuAn";
            
            if(project.Count>0)
            {
                maDuan = Convert.ToInt32(project[0]);
                foreach (var s in project)
                {
                    cbb.PropertiesComboBox.Items.Add(s.TenDuAn, s.MaDuAn);
                    lDuAn.Add(s.MaDuAn);
                }
            }
            
            //cbb.PropertiesComboBox.DataSource = project            cbb.
        }
        protected void LoadGrv()
        {
            //  var us = ((SessionUser)Session[SessionConst.SES_USER]).NguoiSuDung.UserName;
            //   var lUs = (from uw in DaoHelper.Entities.UserWarnings
            //    join p in DaoHelper.Entities.DuAns on uw.MaDuAn equals p.MaDuAn
            //    join r in DaoHelper.Entities.PhanQuyenDuAns on p.MaDuAn equals r.MaDuAn
            //    where (r.UserName == us)
            //    select new
            //        {
            //            uw.Id,
            //            uw.MaDuAn,
            //            uw.MaThietBi,
            //            uw.MaSensor,
            //            uw.UserName
            //         }).ToList();
            //var dt = new DataTable();
            //dt.Columns.Add("Id", typeof (Int32));
            //dt.Columns.Add("MaDuAn", typeof(Int32));
            //dt.Columns.Add("MaThietBi", typeof(string));
            //dt.Columns.Add("MaSensor", typeof(string));
            //dt.Columns.Add("UserName", typeof(string));
            //foreach (var lU in lUs)
            //{
            //    var dr = dt.NewRow();
            //    dr["Id"] = lU.Id;
            //    dr["MaDuAn"] = lU.MaDuAn;
            //    dr["MaThietBi"] = lU.MaThietBi;
            //    dr["MaSensor"] = lU.MaSensor;
            //    dr["UserName"] = lU.UserName;
            //    dt.Rows.Add(dr);
            //}
            //Session["USER_WARNING"] = dt;
            //grvData.DataSource = dt;
            //grvData.DataBind();
        }
        protected void grvData_RowDeleting(object sender, DevExpress.Web.Data.ASPxDataDeletingEventArgs e)
        {
            //try
            //{
            //    int id = Convert.ToInt32(e.Values["Id"]);
            //    var s = (from i in DaoHelper.Entities.UserWarnings
            //             where (i.Id == id)
            //             select i).FirstOrDefault();
            //    if (s == null)
            //        throw new ArgumentException("Delete không thành công!");
            //    DaoHelper.Entities.UserWarnings.Remove(s);
            //    DaoHelper.Entities.SaveChanges();

            //}
            //catch (Exception)
            //{

            //    throw new Exception("Delete không thành công. Vui lòng thử lại.");
            //}
            //e.Cancel = true;
            //grvData.CancelEdit();
            //LoadGrv();
        }

        protected void grvData_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
        {
            //try
            //{
            //    grvData.DoRowValidation();
            //    int maDuAn = Convert.ToInt32(e.NewValues["MaDuAn"].ToString());
            //    string maThietBi = e.NewValues["MaThietBi"].ToString();
            //    string maSensor = e.NewValues["MaSensor"].ToString();
            //    string userName = e.NewValues["UserName"].ToString();
               
            //    var warningValue = (from i in DaoHelper.Entities.UserWarnings
            //                        where (i.MaSensor == maSensor && i.MaDuAn == maDuAn && i.MaThietBi == maThietBi && i.UserName == userName)
            //                        select i).FirstOrDefault();
            //    if (warningValue != null)
            //        throw new ArgumentException("Thoong tin cảnh báo đã tồn tại.");
            //    else
            //    {
            //        var newValue = new UserWarning();
            //        newValue.MaSensor = maSensor;
            //        newValue.MaDuAn = maDuAn;
            //        newValue.MaThietBi = maThietBi;
            //        newValue.UserName = userName;
            //        DaoHelper.Entities.UserWarnings.Add(newValue);
            //        DaoHelper.Entities.SaveChanges();
            //    }

            //}
            //catch (ArgumentException)
            //{
            //    throw;
            //}
            //catch (Exception)
            //{

            //    throw new Exception("Thêm mới không thành công. Vui lòng thử lại.");
            //}
            //e.Cancel = true;
            //grvData.CancelEdit();
            //LoadGrv();
        }
        protected void grvData_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
        {
            //try
            //{
            //    int maDuAn = Convert.ToInt32(e.NewValues["MaDuAn"].ToString());
            //    string maThietBi = e.NewValues["MaThietBi"].ToString();
            //    string maSensor = e.NewValues["MaSensor"].ToString();
            //    string userName = e.NewValues["UserName"].ToString();
            //    var warningValue = (from i in DaoHelper.Entities.UserWarnings
            //                        where (i.MaSensor == maSensor && i.MaDuAn == maDuAn && i.MaThietBi == maThietBi && i.UserName == userName)
            //                        select i).FirstOrDefault();
            //    if (warningValue != null)
            //        throw new ArgumentException("Thong tin cảnh báo đã tồn tại.");

            //    var dr = grvData.GetDataRow(grvData.EditingRowVisibleIndex);
            //    int id = Convert.ToInt32(dr["Id"].ToString());
            //    var s = (from i in DaoHelper.Entities.UserWarnings
            //             where (i.Id == id)
            //             select i).FirstOrDefault();
            //    if (s == null)
            //        throw new ArgumentException("Update không thành công!");

            //    s.MaDuAn = Convert.ToInt32(e.NewValues["MaDuAn"].ToString());
            //    s.MaThietBi = e.NewValues["MaThietBi"].ToString();
            //    s.MaSensor = e.NewValues["MaSensor"].ToString();
            //    s.UserName = e.NewValues["UserName"].ToString();
            //    DaoHelper.Entities.SaveChanges();
            //}
            //catch (ArgumentException)
            //{
            //    throw;
            //}
            //catch (Exception)
            //{
            //    throw new Exception("Update không thành công. Vui lòng thử lại.");

            //}
            //e.Cancel = true;
            //grvData.CancelEdit();
            //LoadGrv();
        }

        protected void grvData_CustomCallback(object sender, ASPxGridViewCustomCallbackEventArgs e)
        {
            var param = e.Parameters.ToString().Split('@');
            if(param.Length<2)
                return;
            if (param[1] == "ContentPlaceHolder1_UcUserWarningManager_grvData_DXEditor2")
            {
                maDuan = Convert.ToInt32(param[0]);
                LoadThietBiCbbByDuAn();
                if(!string.IsNullOrEmpty(maThietBi))
                    LoadSensorCbbByThietBi();
            }
            else if (param[1] == "ContentPlaceHolder1_UcUserWarningManager_grvData_DXEditor3")
            {
                maThietBi = param[0].ToString();
                LoadSensorCbbByThietBi();
                LoadThietBiCbbByDuAn();
            }
           
            
        }
        
    }
}